import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.GameCanvas;
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.MessageListener;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author Binh
 */
public class SunnetCanvas extends GameCanvas implements MessageListener, GoldItem, CommandListener, Runnable {

    // public Form1 form;
    public boolean isMenu = true;
    int curMenu = 0, minMenu = 0, soundid = 1;
    public static int langId = 1;
    int xL = 0, yL = 0;
    public String[] menu, menuViet = new String[]{"Ván mới", "Thêm 30 lượt", "Bật âm thanh", "English", "Tải game khác", "Điểm cao", "Thoát", "Tiếp tục"};
    public String[] menuoffViet = new String[]{"Ván mới", "Thêm 30 lượt", "Tắt âm thanh", "English", "Tải game khác", "Điểm cao", "Thoát", "Tiếp tục"};
    public String[] menuEnglish = new String[]{"New Game", "Buy 30 times", "Sound On", "Tiếng Việt", "Get more games", "High Score", "Exit", "Continue"};
    public String[] menuoffEnglish = new String[]{"New Game", "Buy 30 times", "Sound Off", "Tiếng Việt", "Get more games", "High Score", "Exit", "Continue"};
    Font fontMenu = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_MEDIUM);
    Font fontTextMenu = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_SMALL);
    public static int menuflag = 1;
    int ff;
    private int style = 1;
    public static int DELAY_DEFAULT = 100;
    private int mode = 0;
    Mymidlet mymidlet;

    public static int VERTICAL = 1;
    public static int HORIZONTAL = 0;

    private static bestscore bestScore;
    private static int gameID = 28;
    private static String serviceNum_score = "6511";
    public static String serviceNum_gold = "6711";
    public static String goldSMS = "GMHCLT";

    private Alert noTurnAlert;
    private Alert buyAlert;
    private Command buyCommand = new Command("Mua", Command.ITEM, 0);
    private Command cancelCommand = new Command("Dừng", Command.ITEM, 0);

    private static boolean isRunning;
    private static int delay;
    private static int keycode = 9999;

    private static SunnetFlash sunnetFlash;
    public static SunnetCanvas instance;
    private static Form1 form1;
    private static Form2 form2;
    public static MyCanvas mycanvas;
    public static highscore scoreCanvas;

    public static final byte SCREEN_FLASH = 0;
    public static final byte SCREEN_MENU = 1;
    public static final byte SCREEN_FORM1 = 2;
    public static final byte SCREEN_FORM2 = 3;
    public static final byte SCREEN_GAME = 4;
    public static final byte SCREEN_SCORE = 5;
    public static byte curScreen;


    public SunnetCanvas(Mymidlet mymidlet) {
        super(false);
        instance = this;
        this.setFullScreenMode(true);
        this.mymidlet = mymidlet;
        isRunning = false;
        setMenu();
    }

    private void setMenu(){
        if (langId == 0) {
            if (soundid == 1)
                menu = menuoffEnglish;
            else
                menu = menuEnglish;
        } else {
            if (soundid == 1)
                menu = menuoffViet;
            else
                menu = menuViet;
        }
    }

    public void start(){
        isRunning = true;
        Thread t = new Thread(this);
        t.start();
    }

    public static SunnetFlash getSunnetFlash(){
        if(sunnetFlash == null)
            sunnetFlash = new SunnetFlash();

        return sunnetFlash;
    }

    public static Form1 getForm1(){
        if(form1 == null){
            form1 = new Form1();
        }
        return form1;
    }

    public static Form2 getForm2(){
        if(form2 == null){
            form2 = new Form2();
        }
        return form2;
    }

    public static MyCanvas getMyCanvas(){
        if(mycanvas == null){
            try {
                mycanvas = new MyCanvas(Mymidlet.instance);
            } catch (Exception ex) {}
        }

        return mycanvas;
    }

    public static highscore getHighScore(){
        if(scoreCanvas == null)
            scoreCanvas = new highscore();

        return scoreCanvas;
    }

    public void run() {
        Graphics g = getGraphics();
        if(Mymidlet.width == -1){
            Mymidlet.width = getWidth();
            Mymidlet.height = getHeight();
        }
        long memo;

        while(isRunning){
            memo = System.currentTimeMillis();
            if(curScreen == SCREEN_FLASH){
                delay = getSunnetFlash().getDelay();
                if(keycode != 9999){
                    keycode = 9999;
                }
                getSunnetFlash().paint(g);
            }
            else if(curScreen == SCREEN_MENU){
                delay = getDelay();
                if(keycode != 9999){
                    pressKey(keycode);
                    keycode = 9999;
                }
                paintMenu(g);
            }
            else if(curScreen == SCREEN_FORM1){
                delay = getForm1().getDelay();
                if(keycode != 9999){
                    getForm1().keyPressed(keycode);
                    keycode = 9999;
                }
                getForm1().paint(g);
            }
            else if(curScreen == SCREEN_FORM2){
                delay = getForm2().getDelay();
                if(keycode != 9999){
                    getForm2().keyPressed(keycode);
                    keycode = 9999;
                }
                getForm2().paint(g);
            }
            else if(curScreen == SCREEN_GAME){
                delay = getMyCanvas().getDelay();
                if(keycode != 9999){
                    getMyCanvas().keyPressed(keycode);
                    keycode = 9999;
                }
                getMyCanvas().paint(g);
            }
            else if(curScreen == SCREEN_SCORE){
                delay = getHighScore().getDelay();
                if(keycode != 9999){
                    getHighScore().keyPressed(keycode);
                    keycode = 9999;
                }
                getHighScore().paint(g);
            }


            this.flushGraphics(0, 0, Mymidlet.width, Mymidlet.height);

            try {
                Thread.sleep(Math.max(0, delay - System.currentTimeMillis() + memo));
            } catch (InterruptedException ex) {}
        }
    }

    protected void keyPressed(int keyCode) {
        if(SunnetCanvas.keycode == 9999){
            SunnetCanvas.keycode = keyCode;
        }
    }

    public int getDelay(){
        return DELAY_DEFAULT;
    }

    public void paintMenu(Graphics g) {
        g.setColor(0, 0, 0);
        g.fillRect(0, 0, Mymidlet.width, Mymidlet.height);
        drawMenu(g, Mymidlet.width / 2, (Mymidlet.height - fontMenu.getHeight() * 5) / 2);
    }

    public void drawMenu(Graphics g, int x, int y) {
        VERTICAL = 1;
        HORIZONTAL = 0;

        g.setColor(255, 225, 0);
        for (int q = 1; q <= Mymidlet.width / 4 + 1; q++) {
            for (int p = 1; p <= 2; p++) {
                if ((p == 1) || ((q % 2) == 0)) {
                    g.fillRect(q * 3 - 1 + Mymidlet.width / 8, p * 3 + (Mymidlet.height - 7 * fontMenu.getHeight()) / 2 - 4, 2, 2);

                }
                if ((p == 2) || ((q % 2) == 0)) {
                    g.fillRect(q * 3 - 1 + Mymidlet.width / 8, p * 3 + (Mymidlet.height + 7 * fontMenu.getHeight()) / 2 - 4, 2, 2);
                }
            }
        }

        for (int q = 1; q <= 2; q++) {
            for (int p = 1; p <= 7 * fontMenu.getHeight() / 3 + 1; p++) {
                if ((q == 1) || (p % 2) == 0) {
                    g.fillRect(q * 3 - 1 + Mymidlet.width / 8, p * 3 + (Mymidlet.height - 7 * fontMenu.getHeight()) / 2 - 4, 2, 2);
                }
                if ((q == 2) || ((p % 2) == 0)) {
                    g.fillRect(q * 3 - 1 + Mymidlet.width / 4 * 3 + Mymidlet.width / 8 - 6 + 3, p * 3 + (Mymidlet.height - 7 * fontMenu.getHeight()) / 2 - 4, 2, 2);
                }
            }
        }

        if(Mymidlet.width<180)
            g.setFont(fontTextMenu);
        else
            g.setFont(fontMenu);

        for (int i = minMenu; i < minMenu + 5; i++) {
            if (curMenu == i)
                g.setColor(0xffffff);
            else
                g.setColor(0xff0000);

            if (Mymidlet.width < 200)
                g.drawString(menu[i], x - fontTextMenu.stringWidth(menu[i]) / 2, y + (i - minMenu) * (fontMenu.getHeight() * 57 / 56), 0);
            else
                g.drawString(menu[i], x - fontTextMenu.stringWidth(menu[i]) / 2, y + (i - minMenu) * (fontMenu.getHeight() * 57 / 56), 0);

        }

        g.setFont(fontTextMenu);
        g.setColor(255, 0, 0);
        g.drawString("Số lượt chơi: " + mymidlet.getTimes(), 10, 20, 0);
    }

    private void pressKey(int keycode){
        int instantkeyCode = KeyCodeAdapter.getInstance().adoptKeyCode(keycode);
        switch (instantkeyCode) {
            case KeyCodeAdapter.DOWN_KEY:
                downKey();
                return;
            case KeyCodeAdapter.UP_KEY:
                upKey();
                return;
            case KeyCodeAdapter.CENTER_KEY:
                try {
                    fireKey();
                } catch (Exception ex) {}
                return;
            case KeyCodeAdapter.SOFT_KEY_MIDDLE_INTERNET:
                try {
                    fireKey();
                } catch (Exception ex) {}
                return;
            case KeyCodeAdapter.SOFT_KEY_LEFT:
                menuLeftKey();
                return;
            case KeyCodeAdapter.SOFT_KEY_RIGHT:
                menuRightKey();
                return;
        }
    }

    public void upKey() {
        if (curMenu > 0) {
            if (minMenu == curMenu) {
                minMenu--;
            }
            curMenu--;
        } else {
            curMenu = menu.length - 1;
            minMenu = menu.length - 5;
        }

    }

    public void downKey() {
        if (curMenu < (menu.length - 1)) {
            if (curMenu == minMenu + 4) {
                minMenu++;
            }
            curMenu++;
        } else {
            curMenu = 0;
            minMenu = 0;
        }
    }

    public void fireKey() throws Exception {
        if (isMenu) {
            switch (curMenu) {
                case 0:
                    if(mymidlet.getTimes() > 0){
                        mymidlet.setTimes(mymidlet.getTimes() - 1);
                        if (soundid == 0)
                            getForm1().form1flagmusic = 0;
                        else if (soundid == 1)
                            getForm1().form1flagmusic = 1;
                        curScreen = SCREEN_FORM1;
                    }
                    else{
                        mymidlet.display.setCurrent(getNoTurnAlert(), this);
                    }
                    return;
                case 1:
                    mymidlet.display.setCurrent(getBuyAlert(), this);
                    return;
                case 2:
                    if (getMyCanvas().flagmusic == 1)
                        getMyCanvas().flagmusic = 0;
                    else
                        getMyCanvas().flagmusic = 1;

                    if (soundid == 0) {
                        soundid = 1;
                        if (langId == 1) {
                            menuflag = 1;
                        } else {
                            menuflag = 3;
                        }
                    } else {
                        soundid = 0;
                        if (langId == 1) {
                            menuflag = 0;
                        } else {
                            menuflag = 2;
                        }
                    }
                    setMenu();
                    return;
                case 3:
                    if (langId == 1) {
                        langId = 0;
                        if (soundid == 0) {
                            menuflag = 2;
                        } else {
                            menuflag = 3;
                        }
                    } else {
                        langId = 1;
                        if (soundid == 0) {
                            menuflag = 0;
                        } else {
                            menuflag = 1;
                        }
                    }
                    setMenu();
                    return;
                case 4:
                    mymidlet.platformRequest("http://m.qplay.vn");
                    mymidlet.destroyApp(true);
                    return;
                case 5:
                    getHighScore().getScore();
                    curScreen = SCREEN_SCORE;
                    return;
                case 6:
                    mymidlet.destroyApp(true);
                    mymidlet.notifyDestroyed();
                    return;
                case 7:
                    if (getMyCanvas().isplay == false && getMyCanvas().flagall != 1) {
                        getMyCanvas().start();
                        curScreen = SCREEN_GAME;
                        return;
                    } else {
                        return;
                    }
            }
        }
    }

    public void menuLeftKey() {
    }

    public void menuRightKey() {
    }

    public Alert getNoTurnAlert(){
        if(noTurnAlert == null){
            noTurnAlert = new Alert("Bạn đã hết lượt!", "Bạn có muốn mua thêm 30 lượt chơi nữa ko? (SMS: 15.000VND)", null, AlertType.CONFIRMATION);
            noTurnAlert.setTimeout(Alert.FOREVER);
            noTurnAlert.addCommand(buyCommand);
            noTurnAlert.addCommand(cancelCommand);
            noTurnAlert.setCommandListener(this);
        }
        return noTurnAlert;
    }

    public Alert getBuyAlert(){
        if(buyAlert == null){
            buyAlert = new Alert("", "Bạn có muốn mua thêm 30 lượt chơi nữa ko? (SMS: 15.000VND)", null, AlertType.CONFIRMATION);
            buyAlert.setTimeout(Alert.FOREVER);
            buyAlert.addCommand(buyCommand);
            buyAlert.addCommand(cancelCommand);
            buyAlert.setCommandListener(this);
        }
        return buyAlert;
    }

    public static bestscore getBestScore(){
        if(bestScore == null){
            bestScore = new bestscore(null, Mymidlet.instance);
        }

        if(langId == 1)
            bestScore.setTitle("Điểm cao");
        else if(langId == 0)
            bestScore.setTitle("Your score");

        bestscore.scoreStr.setText(MyCanvas.str);
        return bestScore;
    }

    public static SendMessageItem getUpScoreMessage(String name, int score){
        SendMessageItem sendSMS = new SendMessageItem("HCJ " + name + "+" + gameID + "+" + score + "+", serviceNum_score, null);
        return sendSMS;
    }

    public void notifyIncomingMessage(MessageConnection mc) {
    }

    public void setGold() {
        this.mymidlet.setTimes(this.mymidlet.getTimes()+30);
    }

    public void commandAction(Command c, Displayable d) {
        if(c == buyCommand){
            //Send sms
            try {
                //Lệnh gửi tin nhắn đến tổng đài
                SendMessageItem sendSMS = new SendMessageItem(goldSMS, serviceNum_gold, this);
                new Thread(sendSMS).start();
                mymidlet.display.setCurrent(this);
                this.setFullScreenMode(true);
            } catch (Exception ex) {}
        }
        else if(c == cancelCommand){
            mymidlet.display.setCurrent(this);
            this.setFullScreenMode(true);
        }
    }


}
